$.ajax({
    url:constUrl+"SearchQueueListServlet",
    type:'post',
    dataType:'json',
    success: function(responseText) {
        if (responseText.result=="success"){
            var queue ='';
            for(var i=0;i<responseText.data.length;i++){
                queue+='<option value="'+(responseText.data[i].QUEUE_NAME)+'" >'+responseText.data[i].QUEUE_NAME+'</option>'
            }
            $("#job_queue").append(queue);
        }
    },
    complete: function() {
    },
    error: function() {
    }
});

$.ajax({
    url:constUrl+"HostGroupList",
    type:'post',
    dataType:'json',
    data:{
        method: "getAllGroup"
    },
    success: function(responseText) {
        if (responseText.result=="success"){
            var group ='';
            for(var i=0;i<responseText.message.length;i++){
                group+='<option value="'+(responseText.message[i].GROUP_NAME)+'" >'+responseText.message[i].GROUP_NAME+'</option>'
            }
            $("#node_group").append(group);
        }
    },
    complete: function() {
    },
    error: function() {
    }
});

$('input[type=radio][name=MPI]').change(function() {
    if (this.value == 'true') {
        $("#mpinum_div").css("display","block");
    }
    else if (this.value == 'false') {
        $("#mpinum_div").css("display","none");
    }
});

$('input[type=radio][name=work_style]').change(function() {
    if (this.value == 'realTime') {
        $("#time_div").css("display","none");
        $("#sTime_div").css("display","none");
        $("#eTime_div").css("display","none");
    }
    else if (this.value == 'definiteTime') {
        $("#time_div").css("display","block");
        $("#sTime_div").css("display","block");
        var time = new Date();
        $('#sTime').datetimepicker('update', time);
        $("#eTime_div").css("display","block");
    }
});


$("#fileButton").click(function (e) {
    var fileElem = document.getElementById("file");
    if (fileElem) {
        fileElem.click();
    }
    e.preventDefault();
})

$('#sTime').datetimepicker();

$('#eTime').datetimepicker();

$('#sTime')
    .datetimepicker()
    .on('changeDate', function(ev){
        var eTime = $('#eTime').val();
        if(eTime!=""){
            var eTimeDate = new Date(eTime);
            if(ev.date.valueOf()>   eTimeDate.getTime()){
                layer.alert('开始日期应小于结束日期，请重选！');
                $("#sTime").val("");
            }
        }
        var sTime=$("#sTime").val();
        if(sTime!==""&&sTime!==null){
            $("#check_sTime_div").hide();
            $("#sTime").css("border-color","#1ece20");
        }else{
            $("#sTime").css("border-color","red");
            $("#check_sTime_div").css("color","red")
            $("#check_sTime_div").show();
        }
    });

$('#eTime')
    .datetimepicker()
    .on('changeDate', function(ev){
        var sTime = $('#sTime').val();
        if(sTime!=""){
            var sTimeDate = new Date(sTime);
            if(ev.date.valueOf()<sTimeDate.getTime()){
                layer.alert('结束日期应大于开始日期，请重选！');
                $("#eTime").val("");
            }
        }
        var eTime=$("#eTime").val();
        if(eTime!==""&&eTime!==null){
            $("#check_eTime_div").hide();
            $("#eTime").css("border-color","#1ece20");
        }else{
            $("#eTime").css("border-color","red");
            $("#check_eTime_div").css("color","red")
            $("#check_eTime_div").show();
        }
    });

//详情预览
function checkInfo() {
    var name = $("#name").val();
    var command = $("#command").val();
    var paramFlieresString=$("#file").val();
    var str = paramFlieresString.split("\\");
    var paramFlieres = str[str.length-1];
    var scheduling_strategy = $("#scheduling_strategy").val();
    var priority = $("#priority").val();
    var job_queue = $("#job_queue").val();
    var node_group = $("#node_group").val();
    var work_style = $("input[name='work_style']:checked").val();
    var work_style_string;
    if (work_style=="definiteTime"){
        work_style_string = "定时作业";
    } else {
        work_style_string = "实时作业";
    }
    var sTime = $("#sTime").val();
    var eTime = $("#eTime").val();
    var memorynum = $("#memorynum").val();
    var cpunum = $("#cpunum").val();
    var GPU = $("input[name='GPU']:checked").val();
    var GPU_string;
    if (GPU=="true"){
        GPU_string = "是";
    } else {
        GPU_string = "否";
    }
    var MPI = $("input[name='MPI']:checked").val();
    var MPI_string;
    if (MPI=="true"){
        MPI_string = "是";
    } else {
        MPI_string = "否";
    }
    var mpinum = $("#mpinum").val();


    var tableHtml = '<div class="am-u-sm-12 am-u-md-12" id="infoTable"><table class="am-table am-table-bordered am-table-radius am-table-striped">' +
        '<tr><td style="width: 150px">作业名称</td><td  style="width: 295px">'+name+'</td><td style="width: 150px">依赖文件</td><td style="width: 295px">'+paramFlieres+'</td></tr>' +
        '<tr><td>调度策略</td><td>'+scheduling_strategy+'</td><td>优先级</td><td>'+priority+'</td></tr>' +
        '<tr><td>作业队列</td><td>'+job_queue+'</td><td>节点分组</td><td>'+node_group+'</td></tr>' +
        '<tr><td>作业类型</td><td>'+work_style_string+'</td><td></td><td></td></tr>';
    if (work_style=="definiteTime"){
        tableHtml += '<tr><td>开始时间</td><td>'+sTime+'</td><td>结束时间</td><td>'+eTime+'</td></tr>';
    }
    tableHtml += '<tr><td>内存使用量</td><td>'+memorynum+'</td><td>所需CPU核数</td><td>'+cpunum+'</td></tr>';
    if (MPI=="true"){
        tableHtml += '<tr><td>是否使用GPU</td><td>'+GPU_string+'</td><td></td><td></td></tr>' +
            '<tr><td>是否为MPI</td><td>'+MPI_string+'</td><td>MPI进程数</td><td>'+mpinum+'</td></tr>';
    } else {
        tableHtml += '<tr><td>是否使用GPU</td><td>'+GPU_string+'</td><td>是否使用GPU</td><td>'+MPI_string+'</td></tr>';
    }

    tableHtml += '</table>' +
        '<table class="am-table am-table-bordered am-table-radius am-table-striped">' +
        '<tr><td style="width: 150px">执行命令</td><td>'+command+'</td></tr>' +
        '</table></div>';


    $("#deleteLable").html(tableHtml);

}

//验证表单
$(document).ready(function(){
    $("#check_name_div").hide();
    $("#check_command_div").hide();
    $("#check_file_div").hide();
    $("#check_scheduling_div").hide();
    $("#check_priority_div").hide();
    $("#check_jobqueue_div").hide();
    $("#check_nodegroup_div").hide();
    $("#check_sTime_div").hide();
    $("#check_eTime_div").hide();
    $("#check_memorynum_div").hide();
    $("#check_cpunum_div").hide();
    $("#check_mpinum_div").hide();
    $("#check_platform_div").hide();


    //作业名称验证
    $("#name").blur(function(){
        var Name=$("#name").val();
        if(Name!==""){
            $("#command").focus();
            $("#check_name_div").hide();
            $("#name").css("border-color","#1ece20");
        }else{
            $("#name").css("border-color","red");
            $("#check_name_div").css("color","red")
            $("#check_name_div").show();
        }
    });


    //执行命令验证
    $("#command").blur(function(){
        var command=$("#command").val();
        if(command!==""){
            $("#scheduling_strategy").focus();
            $("#command").css("background-color","white");
            $("#command").css("border-color","#1ece20");
            $("#check_command_div").hide();
        }else{
            $("#command").css("border-color","red");
            $("#command").css("color","red");
            $("#check_command_div").show();
        }
    });

    //调度策略选择选择
    $("#scheduling_strategy").blur(function(){
        var scheduling_strategy=$("#scheduling_strategy").val();
        if(scheduling_strategy!==""&&scheduling_strategy!==null){
            $("#priority").focus();
            $("#check_scheduling_div").hide();
            $("#scheduling_strategy").css("border-color","#1ece20");
        }else{
            $("#scheduling_strategy").css("border-color","red");
            $("#check_scheduling_div").css("color","red")
            $("#check_scheduling_div").show();
        }
    });
    //作业优先级验证
    $("#priority").blur(function(){
        var priority=$("#priority").val();
        if(priority!==""&&priority!==null){
            $("#job_queue").focus();
            $("#check_priority_div").hide();
            $("#priority").css("border-color","#1ece20");
        }else{
            $("#priority").css("border-color","red");
            $("#check_priority_div").css("color","red")
            $("#check_priority_div").show();
        }
    });

  /*  $("#job_queue").blur(function(){
        var job_queue=$("#job_queue").val();
        if(job_queue!=null&&job_queue!==null){
            $("#node_group").focus();
            $("#check_jobqueue_div").hide();
            $("#job_queue").css("border-color","#1ece20");
        }else{
            $("#job_queue").css("border-color","red");
            $("#check_jobqueue_div").css("color","red")
            $("#check_jobqueue_div").show();
        }
    });

    $("#node_group").blur(function(){
        var node_group=$("#node_group").val();
        if(node_group!==""&&node_group!==null){
            $("#platform").focus()
            $("#check_nodegroup_div").hide();
            $("#node_group").css("border-color","#1ece20");
        }else{
            $("#node_group").css("border-color","red");
            $("#check_nodegroup_div").css("color","red")
            $("#check_nodegroup_div").show();
        }
    });*/

    $("#platform").blur(function(){
        var platform=$("#platform").val();
        if(platform!==""&&platform!==null){
            $("#check_platform_div").hide();
            $("#platform").css("border-color","#1ece20");
        }else{
            $("#platform").css("border-color","red");
            $("#check_platform_div").css("color","red")
            $("#check_platform_div").show();
        }
    });

    $("#sTime").blur(function(){
        var sTime=$("#sTime").val();
        if(sTime!==""&&sTime!==null){
            $("#check_sTime_div").hide();
            $("#sTime").css("border-color","#1ece20");
        }else{
            $("#sTime").css("border-color","red");
            $("#check_sTime_div").css("color","red")
            $("#check_sTime_div").show();
        }
    });

    $("#eTime").blur(function(){
        var eTime=$("#eTime").val();
        if(eTime!==""&&eTime!==null){
            $("#check_eTime_div").hide();
            $("#eTime").css("border-color","#1ece20");
        }else{
            $("#eTime").css("border-color","red");
            $("#check_eTime_div").css("color","red")
            $("#check_eTime_div").show();
        }
    });

  /*  $("#memorynum").blur(function(){
        var memorynum=$("#memorynum").val();
        if(memorynum!==""&&memorynum!==null){
            $("#check_memorynum_div").hide();
            $("#memorynum").css("border-color","#1ece20");
        }else{
            $("#memorynum").css("border-color","red");
            $("#check_memorynum_div").css("color","red")
            $("#check_memorynum_div").show();
        }
    });

    $("#cpunum").blur(function(){
        var cpunum=$("#cpunum").val();
        if(cpunum!==""&&cpunum!==null){
            $("#check_cpunum_div").hide();
            $("#cpunum").css("border-color","#1ece20");
        }else{
            $("#cpunum").css("border-color","red");
            $("#check_cpunum_div").css("color","red")
            $("#check_cpunum_div").show();
        }
    });*/

    $("#mpinum").blur(function(){
        var mpinum=$("#mpinum").val();
        if(mpinum!==""&&mpinum!==null){
            $("#check_mpinum_div").hide();
            $("#mpinum").css("border-color","#1ece20");
        }else{
            $("#mpinum").css("border-color","red");
            $("#check_mpinum_div").css("color","red")
            $("#check_mpinum_div").show();
        }
    });
});

//验证准备
//输入验证器
function InputValidators(){
    this.validators = [];
    this.strategies = {};
}

//添加验证方法
//参数:
//  rule: 验证策略字符串
//  element: 被验证的dom元素
//  errMsg: 验证失败时显示的提示信息
//  value: 被验证的值
InputValidators.prototype.addValidator = function(rule, element, errMsg, value) {
    var that = this;
    var ruleElements = rule.split(":");

    this.validators.push(function() {
        var strategy = ruleElements.shift();
        var params = ruleElements;
        params.unshift(value);
        params.unshift(errMsg);
        params.unshift(element);

        return that.strategies[strategy].apply(that, params);
    });
};

//添加验证策略函数
//参数:
//  name: 策略名称
//  strategy: 策略函数
InputValidators.prototype.addValidationStrategy = function(name, strategy){
    this.strategies[name] = strategy;
};

//从策略对象导入验证策略函数
//参数:
//  strategies: 包含各种策略函数的对象
InputValidators.prototype.importStrategies = function(strategies) {
    for(var strategyName in strategies) {
        this.addValidationStrategy(strategyName, strategies[strategyName]);
    }
};

//验证失败时，将相关的错误信息打包返回
//参数:
//  element: dom元素
//   errMsg: 验证失败时的提示消息
//    value: 被验证的值
InputValidators.prototype.buildInvalidObj = function(element, errMsg, value){
    return {
        'value': value,
        'element': element,
        'errMsg': errMsg
    };
};

//开始验证
InputValidators.prototype.check = function() {
    for(var i = 0, validator; validator = this.validators[i++];){
        var result = validator();
        if(result) {
            return result;
        }
    }
};

//验证策略对象，包含默认的验证策略函数
var validationStrategies = {
    isNoEmpty: function(element, errMsg, value) {
        if(value === '') {
            return this.buildInvalidObj(element, errMsg, value );
        }
    },
    isNoUndefined: function(element, errMsg, value) {
        if(value === "undefined") {
            return this.buildInvalidObj(element, errMsg, value );
        }
    },
    isInteger:function (element, errMsg, value) {
        var reg = /^[0-9]*[1-9][0-9]*$/ ;
        if(!reg.test(value)){
            return this.buildInvalidObj(element, errMsg, value);
        }
    },
    isRight:function (element, errMsg, value) {
        if(value>100){
            return this.buildInvalidObj(element, errMsg, value);
        }
    },
    isNotEmpty:function (element, errMsg, value) {
        var fdstrat = value.indexOf(".");
        if(fdstrat==-1||value.length<=1){
            return this.buildInvalidObj(element, errMsg, value);
        }
    },
    isCheck:function (element, errMsg, value) {
        var isValue="";
        for(var i=0;i<value.length;i++)
        {
            if(value[i].checked)
            {
                isValue=value[i].value;
                break;
            }
            else
            {
                continue;
            }
        }

        if(isValue==""){
            return this.buildInvalidObj(element, errMsg, value);
        }
    },
    minLength: function(element, errMsg, value, length) {
        if(value.length < length){
            return this.buildInvalidObj(element, errMsg, value);
        }
    },

    maxLength: function(element, errMsg, value, length) {
        if(value.length > length){
            return this.buildInvalidObj(element, errMsg, value);
        }
    },

    isMail: function(element, errMsg, value, length) {
        var reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
        if(!reg.test(value)){
            return this.buildInvalidObj(element, errMsg, value);
        }
    }
};


var isSubmit = false
//提交表单
function submit()
{
    if(!isSubmit){
        isSubmit = true;
        var name = $("#name").val();
        var command = $("#command").val();
        var scheduling_strategy = $("#scheduling_strategy").val();
        var priority = $("#priority").val();
        var job_queue = $("#job_queue").val();
        var node_group = $("#node_group").val();
        var work_style = $("input[name='work_style']:checked").val();
        var platform = $("#platform").val();
        var sTime = $("#sTime").val();
        var eTime = $("#eTime").val();
        var memorynum = $("#memorynum").val();
        var cpunum = $("#cpunum").val();
        var GPU = $("input[name='GPU']:checked").val();
        var MPI = $("input[name='MPI']:checked").val();
        var mpinum = $("#mpinum").val();
        var registerinfo = {
            name:name,
            command:command,
            scheduling_strategy:scheduling_strategy,
            priority:priority,
            job_queue:job_queue,
            node_group:node_group,
            work_style:work_style,
            osType:platform,
            sTime:sTime,
            eTime:eTime,
            memorynum:memorynum,
            cpunum:cpunum,
            GPU:GPU,
            MPI:MPI,
            mpinum:+mpinum
            };

        //进行验证
        var validators = new  InputValidators();

        validators.importStrategies(validationStrategies);

        validators.addValidationStrategy('isEqual',  function(element, errMsg, value1, value2) {
            if(value1 !== value2) {
                return this.buildInvalidObj(element, errMsg, value1 );
            }
        });

        var Vname = document.getElementById('name');
        validators.addValidator('isNoEmpty', Vname, '作业名称未填写，请返回填写', Vname.value);

        var Vcommand = document.getElementById('command');
        validators.addValidator('isNoEmpty', Vcommand, '执行命令未填写，请返回填写', Vcommand.value);

        var Vscheduling_strategy = document.getElementById('scheduling_strategy');
        validators.addValidator('isNoEmpty', Vscheduling_strategy, '调度策略未选择，请返回选择', Vscheduling_strategy.value);

        var Vpriority = document.getElementById('priority');
        validators.addValidator('isNoEmpty', Vpriority, '作业优先级未填写，请返回填写', Vpriority.value);
        //文件
        var paramFlieresString=$("#file");
        var str = paramFlieresString.val().split("\\");
        var paramFlieres = str[str.length-1];
        validators.addValidator('isNoEmpty', paramFlieresString, '没有选择文件，请返回选择文件', paramFlieres);

       /* var Vjob_queue = document.getElementById('job_queue');
        validators.addValidator('isNoEmpty', Vjob_queue, '作业队列未选择，请返回选择', Vjob_queue.value);

        var Vnode_group =document.getElementById("node_group");
        validators.addValidator('isNoEmpty', Vnode_group, '节点分组未选择，请返回选择', Vnode_group.value);*/

        var Vplatform =document.getElementById("platform");
        validators.addValidator('isNoEmpty', Vplatform, '执行平台未选择，请返回选择', Vplatform.value);

        var Vwork_style=document.getElementsByName("work_style");
        validators.addValidator('isCheck', Vwork_style, '作业类型未选择，请返回选择', Vwork_style);

        if (work_style=="definiteTime"){
            var VsTime =document.getElementById("sTime");
            validators.addValidator('isNoEmpty', VsTime, '开始时间未填写，请返回填写', VsTime.value);

            var VeTime =document.getElementById("eTime");
            validators.addValidator('isNoEmpty', VeTime, '结束时间未填写，请返回填写', VeTime.value);
        }

        /*var Vmemorynum =document.getElementById("memorynum");
        validators.addValidator('isNoEmpty', Vmemorynum, '内存使用量未填写，请返回填写', Vmemorynum.value);

        var Vcpunum =document.getElementById("cpunum");
        validators.addValidator('isNoEmpty', Vcpunum, '所需CPU核数未填写，请返回填写', Vcpunum.value);*/

        var VGPU=document.getElementsByName("GPU");
        validators.addValidator('isCheck', VGPU, '请选择是否使用GPU', VGPU);

        var VMPI=document.getElementsByName("MPI");
        validators.addValidator('isCheck', VMPI, '请选择是否使用MPI', VMPI);

        if (MPI=="true"){
            var Vmpinum =document.getElementById("mpinum");
            validators.addValidator('isNoEmpty', Vmpinum, 'MPI进程数未填写，请返回填写', Vmpinum.value);
        }

        var result = validators.check();
        if(result){
            layer.msg(result.errMsg);
            // alert(result.errMsg);
            result.element.focus();
            result.element.select();
            return false;
        }

        var fileinfo=document.getElementById("file");
        var registerinfo_json = JSON.stringify(registerinfo);
        console.log(registerinfo_json);
        var file=new FormData();
        file.append('algorithm',registerinfo_json);
        file.append('file',fileinfo.files[0]);

//alert("befor ajax")
        $.ajax({
            type:"POST",
            url:constUrl+"RegisterJob",
            processData: false,
            contentType: false,
            data: file,
            success:function(responseText){
                var res = JSON.stringify(responseText);
                responseText=eval("("+responseText+")");
                if(responseText.result==true)
                {
                    layer.confirm('添加成功！',{
                        btn:['确定']
                    },function () {

                    	window.location.href=constUrl+ "views/job/list.action"
                    })
                }
                else{
                    layer.msg(responseText.message+",请检查是否填写完全！");
                }

            },
            error:function(responseText) {
                isSubmit = false;
                layer.msg('添加失败！!');
            },
        })
    }

}


function fileShowMess() {
    var paramFlieresString=$("#file").val();
    var str = paramFlieresString.split("\\");
    var paramFlieres = str[str.length-1];
    if(paramFlieres!=""){
        $('#fileShow_div').html(paramFlieres);
        $("#fileShow_div").show();

    }else{
        $('#fileShow_div').html('您还没有输入任何东西');
        $("#fileShow_div").show();
    }
}